<template>
  <div class="login-container">
    <div class="box-item desc">
      <div class="welcome">
        <p>欢迎登录 船闸桥梁监管平台</p>
        <p class="sub-welcome">「安全、稳定、高效」的船闸桥梁监管平台</p>
      </div>
      <img class="welcome-img" :src="leftBg2" />
    </div>
    <div class="box-item login">
      <!-- <img class="login-qr" :src="loginQR" /> -->
      <div class="login-title">账号登录</div>
      <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
        <a-form-item name="loginName">
          <a-input v-model:value.trim="loginForm.loginName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.password"
            autocomplete="on"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码：至少三种字符，最小 8 位"
          />
        </a-form-item>
        <a-form-item>
          <div class="btn" @click="onLogin">登录</div>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script setup>
  import { message } from 'ant-design-vue';
  import { onMounted, onUnmounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useRoute } from 'vue-router';
  import { loginApi } from '/@/api/system/login';
  import { api as userApi } from '/@/api/system/user.js';
  import { api as wvpApi } from '/@/api/system/otherApp';
  import { menuApi } from '/@/api/system/menu-api.js';
  import { api as easyLiveApi } from '/@/api/easyLive/index.js';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { LOGIN_DEVICE_ENUM } from '/@/constants/system/login-device-const';
  import { useUserStore } from '/@/store/modules/system/user';
  import loginQR from '/@/assets/images/login/login-qr.png';
  import leftBg2 from '/@/assets/images/login/left-bg2.png';

  import { buildRoutes } from '/@/router/index';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { encryptData } from '/@/lib/encrypt';
  import { localSave } from '/@/utils/local-util.js';
  import LocalStorageKeyConst from '/@/constants/local-storage-key-const.js';

  //--------------------- 登录表单 ---------------------------------

  const loginForm = reactive({
    loginName: 'admin',
    password: '',
    captchaCode: '',
    captchaUuid: '',
    loginDevice: LOGIN_DEVICE_ENUM.PC.value,
  });
  const rules = {
    loginName: [{ required: true, message: '用户名不能为空' }],
    password: [{ required: true, message: '密码不能为空' }],
    captchaCode: [{ required: true, message: '验证码不能为空' }],
  };

  const showPassword = ref(false);
  const router = useRouter();
  const formRef = ref();
  const rememberPwd = ref(false);

  onMounted(() => {
    document.onkeyup = (e) => {
      if (e.keyCode == 13) {
        onLogin();
      }
    };
  });

  onUnmounted(() => {
    document.onkeyup = null;
  });

  //登录
  async function onLogin() {
    formRef.value.validate().then(async () => {
      try {
        SmartLoading.show();
        // 密码加密
        let encryptPasswordForm = Object.assign({}, loginForm, {
          password: encryptData(loginForm.password),
        });
        const res = await loginApi.login({
          params: {
            username: loginForm.loginName,
            password: loginForm.password,
            grant_type: 'password',
            scope: 'server',
          },
        });
        stopRefrestCaptchaInterval();
        const { token_type, access_token } = res;
        res.data = {
          token: `${token_type} ${access_token}`,
        };
        localSave(LocalStorageKeyConst.USER_TOKEN, res.data.token ? res.data.token : '');
        // 获取easyLive的token
        // const liveData = await easyLiveApi.getToken();、
        // localSave(LocalStorageKeyConst.live_TOKEN, `Bearer ${liveData.token || ''}`);
        const userInfo = await userApi.getInfo(loginForm.loginName);
        localSave(LocalStorageKeyConst.USERINFO_TOKEN, userInfo.data ? JSON.stringify(userInfo.data) : '');
        // message.success('登录成功');
        // 构建系统的路由
        const menuTree = await menuApi.getMenu();
        buildRoutes(menuTree.data);
        // 更新用户信息到pinia
        useUserStore().setMenuList(menuTree.data);
        router.push('/monitor');
        // 获取wvp的token
        wvpApi.getWToken().then((res) => {
          if (res.code === 0) {
            localSave(LocalStorageKeyConst.WVP_TOKEN, res.data.accessToken ? res.data.accessToken : '');
          } else {
            // message.error('流媒体连接失败');
          }
        });
      } catch (e) {
        if (e.data && e.data.code !== 0) {
          loginForm.captchaCode = '';
          getCaptcha();
        }
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    });
  }

  //--------------------- 验证码 ---------------------------------

  const captchaBase64Image = ref('');
  async function getCaptcha() {
    try {
      let captchaResult = await loginApi.getCaptcha();
      captchaBase64Image.value = captchaResult.data.captchaBase64Image;
      loginForm.captchaUuid = captchaResult.data.captchaUuid;
      beginRefrestCaptchaInterval(captchaResult.data.expireSeconds);
    } catch (e) {
      console.log(e);
    }
  }

  let refrestCaptchaInterval = null;
  function beginRefrestCaptchaInterval(expireSeconds) {
    if (refrestCaptchaInterval === null) {
      refrestCaptchaInterval = setInterval(getCaptcha, (expireSeconds - 5) * 1000);
    }
  }

  function stopRefrestCaptchaInterval() {
    if (refrestCaptchaInterval != null) {
      clearInterval(refrestCaptchaInterval);
      refrestCaptchaInterval = null;
    }
  }

  // onMounted(getCaptcha);
</script>
<style lang="less" scoped>
  @import './login.less';
</style>
